
export default () => {
    const useToken = () => useState('token')
    const useUser = () => useState('user')
    const useAuthLoading = () => useState('auth_loading', () => true)

    const setToken = (value) => {
        const token = useToken()
        token.value = value
    }
    const setUser = (value) => {
        const user = useUser()
        user.value = value
    }
    const setAuthLoading = (value) => {
        const loading = useAuthLoading()
        loading.value = value
    }

    const login = async ({username, password}) => {
        const res = await request({
            url: '/user/login',
            method: 'POST',
            data: {
                username,
                password
            }
        })
        if (res.code == 200) {
            const token = res.data.token
            useCookie("token", {
                maxAge: 14 * 24 * 60 * 60, // Cookie Token 过期时间为14天
            }).value = token;
            setToken(token)
            setUser(res.data.user)
        }
        return res
    }
    const router = useRouter()
    const initAuth = () => {
        return new Promise(async(resolve, reject) => {
            setAuthLoading(true)
            try {
                const res = await request({
                    url: '/user/token',
                    method: 'GET'
                })
                
                if (res.code == 402) {
                    router.push('/register')
                } else {
                    router.push('/login')
                }

                setUser(res.data?.user)
                resolve(true)
            } catch(error) {
                router.push('/error/500')
                reject(error)
            } finally {
                setAuthLoading(false)
            }
        })
    }
    return {
        login,
        initAuth,
        useUser,
        setUser,
        useAuthLoading
    }
}